<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;

// use GuzzleHttp\Client;
// use GuzzleHttp\Promise;
// use Illuminate\Pagination\LengthAwarePaginator;


class WechatLoginController extends Controller
{

    //获取Access Token
    private function getAccessToken($code){

        $ACCESS_TOKEN = file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.env('WECHAT_LOGIN_APPID').'&secret='.env('WECHAT_LOGIN_APPSECRET').'&code='.$code.'&grant_type=authorization_code');
        return $ACCESS_TOKEN;
    }


    //获取用户信息方法
    private function getUserInfo($access_token,$openid){
        return(file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid));
    }

    //获取登录;
    public function login(Request $request){
        $code = $request->code;
        //获取access_token等信息
        $access_token=$this->getAccessToken($code);
        $assess_tokenArr = json_decode($access_token,true);

        //获取用户信息
        $userinfo = $this->getUserInfo($assess_tokenArr['access_token'],$assess_tokenArr['openid']);
        $wxinfo = json_decode($userinfo,true);

        // 查询日记
        $user = DB::table('users')
            ->select('id','username','email','password')
            ->where('wx_unionid', $wxinfo['unionid'])
            ->first();

        // unionid 字段当且仅当该网站应用已获得该用户的userinfo授权时，才会出现该字段。


            switch ( $_GET['state']){
                case 'login':
                    if($user){    //查询数据库中wx_unionid存在
                        Auth::loginUsingId($user->id,true); // 登录并且记住密码
                        return redirect(route('dashboard'));    //登录后返回仪表盘
                    }else {
                        return redirect(route('register') . '?unionid=' . $wxinfo['unionid']);
                    }
                    break;

                case 'binding':
                    if($user) {    //查询数据库中wx_unionid存在
                        return response()->json(['message' => 'The given data was invalid.', 'errors' => ['unionid' => ['该微信已绑定其他用户名。']]], 422)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
                    }else{
                        DB::table('users')
                            ->where('username', Auth::user()->username)
                            ->update(['wx_unionid' => $wxinfo['unionid']]);

                        return redirect(route('dashboard'));
                    }
                    break;

            }


    }


        // 通过 unionid 获取 openid
// public function getOpenIdByUnionId(Request $request)
// {
//     $accessToken = $this->getGlobalAccessToken(); // 获取全局 Access Token
//     $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$accessToken}";
//     $result = file_get_contents($url);
//     $result = json_decode($result, true);

//     if (isset($result['data']['openid'])) {
//         $openIds = $result['data']['openid'];

//         // 获取所有 wx_unionid 开头包含 orwz 的用户
//         $orwzUsers = DB::table('users')
//             ->where('wx_unionid', 'like', 'orwz%')
//             ->pluck('wx_unionid')
//             ->toArray();

//         $client = new Client();
//         $userInfos = [];

//         // 使用 chunk 方法分块处理 openIds
//         $chunkSize = 100; // 可以根据需要调整块大小
//         $chunks = array_chunk($openIds, $chunkSize);

//         foreach ($chunks as $chunk) {
//             $promises = [];

//             // 创建异步请求
//             foreach ($chunk as $openId) {
//                 $userInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
//                 $promises[] = $client->getAsync($userInfoUrl);
//             }

//             // 等待所有请求完成
//             $responses = Promise\settle($promises)->wait();

//             foreach ($responses as $response) {
//                 if ($response['state'] === 'fulfilled') {
//                     $userInfo = json_decode($response['value']->getBody(), true);
//                     if (isset($userInfo['unionid'])) {
//                         // 对比 unionid 是否在 orwzUsers 列表中
//                         if (!in_array($userInfo['unionid'], $orwzUsers)) {
//                             $userInfos[] = [
//                                 'openid' => $userInfo['openid'],
//                                 'unionid' => $userInfo['unionid']
//                             ];
//                         }
//                     }
//                 }
//             }
//         }

//         // 使用 Laravel 的 Collection 进行分页
//         $currentPage = LengthAwarePaginator::resolveCurrentPage();
//         $perPage = 100;
//         $currentItems = array_slice($userInfos, ($currentPage - 1) * $perPage, $perPage);
//         $paginatedItems = new LengthAwarePaginator($currentItems, count($userInfos), $perPage);

//         // 设置分页的路径
//         $paginatedItems->setPath($request->url());

//         return view('list', ['userInfos' => $paginatedItems]);
//     }

//     return response()->json(['error' => '没有找到匹配的 OpenID'], 404);
// }




//     // 获取全局 Access Token
//     private function getGlobalAccessToken(){
//         $ACCESS_TOKEN = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.env('WECHAT_LOGIN_APPID').'&secret='.env('WECHAT_LOGIN_APPSECRET'));
//         $accessTokenArr = json_decode($ACCESS_TOKEN, true);
//         return $accessTokenArr['access_token'];
//     }


}
